/**
 * 加载图片简化版 CP FROM PL
 * @author Li
 */
;(function ($, w) {

    var LoadImage = function () {
        this.version = 'v1.0';
    };

    LoadImage.prototype = {
        constructor: LoadImage,
        loadImg: function () {
            var imgs = $('img[data-delay]');
            this.loadDelayImg(imgs);
        },   
         /**
         * 功能:将图象的懒加载属性写入src属性，进行图象加载
         *
         * @param imgs{NodeList}
         */
        loadDelayImg: function (imgs) {
            var length = imgs.length, i = 0;
            for (i; i < length; ++i) {
                (function (i) {
                    var img = imgs[i], src;
                    if (img instanceof HTMLElement) {
                        img.setAttribute('load', 'unload');
                        src = img.getAttribute('data-delay');
                        img.addEventListener('load', function () {
                            this.setAttribute('load', 'loaded');
                        });
                        img.addEventListener('error', function () {
                            this.setAttribute('load', 'error');
                            var defaultSrc = this.getAttribute('data-default');
                            if (defaultSrc && defaultSrc!=this.getAttribute('src')) {
                                this.setAttribute('src', defaultSrc);
                            }
                        });
                        if (src)
                            img.setAttribute('src', src);
                    }
                })(i);
            }
        },
        /**
         * 功能:检测img图象是否加载完成
         *
         * @param imgs{NodeList}
         * @returns {boolean}
         */
        delayImgLoaded: function (imgs) {
            var length = imgs.length, i = 0;
            for (; i < length; ++i) {
                var img = imgs[i];
                if (img instanceof HTMLElement) {
                    var load = img.getAttribute('load');
                    if (load === 'unload')
                        return false;
                }
            }
            return true;
        },
        check: function(delayImgs){
            var _this = this, _self = w.self;
            var check = _self.setInterval(function () {
                if (_this.delayImgLoaded(delayImgs)) {
                    _self.clearInterval(check);
                }
            }, 1500);
        }
    };
    w.LoadImage = new LoadImage();
})(jQuery, window);